<?php
/**
 * TODO: enable caching for AJAX data (product list, etc.)
 */

class Backend_ShoppingController extends RCMS_Core_BaseController {

	protected $_configTableArray;

	protected $_smtpConfigArray;

	protected $_domain;

	protected $_smtpHost;

	protected $_smtpLogin;

	protected $_smtpPassword;

	protected $_adminShoppingEmail;

    protected $_error = array ();

	/**
	 * Init function.
	 * @return <void>
	 */
	public function init()
    {
        parent::init();
        $this->_checkLogin(array('addtocart', 'recount', 'viewsc', 'quoteme', 'handlerpaypalaccount', 'handlerpaypalcreditcard', 'counttax', 'rateproduct', 'saveuserdata'));
		$this->_model = new Backend_ShoppingModel();
		$this->_initSmtp();
	}

	/**
	 * This function loads template where user can add and edit a product.
	 * @return <void>
	 */
	public function productAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
        $this->view->productId = intval($this->getRequest()->getParam('id'));
		$this->view->listFolders = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images);
		$this->view->groups = $this->_model->selectGroups();
		$this->view->products = $this->_model->selectAllProducts();
        $this->view->shoppingConfig = $this->_model->selectShoppingConfig();

		//for translator
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}

	/**
	 * This function loads template where user can change config for shopping.
	 * @return <void>
	 */
	public function configAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $this->view->update = false;

        if ($this->getRequest()->isPost()) {
           /* save settings for shopping config */
            $settingsPayPal = array(
                'email'       =>  trim($this->getRequest()->getParam('paypalemail')),
                'signature'   =>  trim($this->getRequest()->getParam('paypalsignature')),
                'user'        =>  trim($this->getRequest()->getParam('paypaluser')),
                'password'    =>  trim($this->getRequest()->getParam('paypalpassword'))
            );

            $data = array (
                'company'               =>  trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('company'))),
                'phone'                 =>  trim($this->getRequest()->getParam('phone')),
                'email'                 =>  trim($this->getRequest()->getParam('email')),
                'address'               =>  trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('address'))),
                'address2'              =>  trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('address2'))),
                'city'                  =>  trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('city'))),
                'state'                 =>  trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('state'))),
                'zip'                   =>  trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('zip'))),
                'country'               =>  trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('country'))),
                'currency'              =>  trim($this->getRequest()->getParam('currency')),
                'gateway'               =>  trim($this->getRequest()->getParam('gateway')),
                'quote'                 =>  (strtolower($this->getRequest()->getParam('quote')) == 'on' ? '1' : '0'),
                'autoquote'             =>  (strtolower($this->getRequest()->getParam('autoquote')) == 'on' ? '1' : '0'),
                'paypal'                =>  serialize($settingsPayPal),
                'company_logo'          =>  trim($this->getRequest()->getParam('company-logo')),
                'policy_page_url'       =>  $this->getWebSiteUrl() . trim($this->getRequest()->getParam('policy-page-name')) . '.html',
				'legal-info'			=>	strip_tags(trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('legal-info')))),
				'deny-int-payment'      =>  (strtolower($this->getRequest()->getParam('deny-int-payment')) == 'on' ? '1' : '0'),
				'use_https'				=>	$this->getRequest()->getParam('use-https')
            );
            if (count($this->_error) == 0){
                foreach ($data as $key => $value) {
                    $this->_model->updateShoppingConfig($key, $value);
                }
                $this->view->error = false;
                $this->view->update = true;
            } else {
                $this->view->error = true;
            }
        }
        /* load settings */
        $this->view->listFolders    = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images);
		$this->view->shoppingConfig = $this->_model->selectShoppingConfig();
        $this->view->pageList       = $this->_model->selectAllPages();
        $this->view->logoCompany    = '';
        if (is_file($this->_config->website->website->path.$this->view->shoppingConfig['company_logo'])) {
            $this->view->logoCompany = $this->view->websiteUrl.$this->view->shoppingConfig['company_logo'];
        }
		//for translator
		echo $this->_translator->processScreen($this->view->render($this->getViewScript()));
	}

        /**
         * Load template which let configure products templates and email templates.
         * @return void
         */
        public function templatesAction()
        {
            $this->_helper->getHelper('layout')->disableLayout();
            $this->_helper->viewRenderer->setNoRender(true);
            $this->view->update = false;

            $generator = new RCMS_Object_Generator_Generator();

            if ($this->getRequest()->isPost()){
                $quoteResponderBody = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('quote-auto-responder-body')));
                $quoteResponderSubj = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('quote-auto-responder-subject')));
                $quoteEmailSubj     = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('quote-email-subject')));
                $quoteEmailBody     = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('quote-email-body')));

                $data = array (
                    'template_product'      =>  trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('template-product'))),
                    'template_prod_list'    =>  trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('template-prod-list'))),
                    'quote_responder_subj'  =>  (!empty($quoteResponderSubj) ? $quoteResponderSubj : 'A new quote request on '.$this->getWebSiteUrl()),
                    'quote_responder_body'  =>  (!empty($quoteResponderBody) ? $quoteResponderBody : $generator->generateQuoteResponderBody()),
                    'quote_email_subj'      =>  (!empty($quoteEmailSubj) ? $quoteEmailSubj : 'Quote'),
                    'quote_email_body'      =>  (!empty($quoteEmailBody) ? $quoteEmailBody : $generator->generateQuoteMailToUser()),
                    );
                foreach ($data as $key => $value) {
                    $this->_model->updateShoppingConfig($key, $value);
                }
                $this->view->update = true;
            }
            unset($generator);
            //load config
            $this->view->shoppingConfig = $this->_model->selectShoppingConfig();
            //show screen
            echo $this->_translator->processScreen($this->view->render($this->getViewScript()));
        }

	/**
	 * This function loads images for selected folder. (AJAX)
	 * @return <string> (json)
	 */
	public function loadimagesAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if ($this->getRequest()->isPost()) {
			$folder = trim($this->getRequest()->getParam('folder'));
			if ($folder === '') { return; }
			$smallImages = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images . $folder . '/small/');
			$path = $this->_config->website->website->url . 'images/' . $folder . '/';
			$contentSmallImages = '<div style="border-bottom:1px solid #7c7c7c;margin-bottom:3px;height:20px;text-align:right;" onclick="this.parentNode.style.display=\'none\';"><span style="cursor:pointer;color:#7c7c7c;font-weight:bold;"> Close </span></div>';
			if (count($smallImages) > 0) {
				foreach ($smallImages as $image) {
					$contentSmallImages .= '<img title="' . $image . '"  onclick="shop.selectImage(\'' . $path . 'small/' . $image . '\');" style="vertical-align:top; margin: 0px 0px 1px 1px;cursor:pointer;" border="0" width="55" src="' . $path . 'small/' . $image .'">';
				}
				$contentSmallImages .= '<div style="clear:both;height:0px;">&nbsp;</div>';
			}
			echo json_encode(array('small' => $contentSmallImages)); return;
		}
	}

	/**
	 * This function adds new group. (AJAX)
	 * @return <string> (json)
	 */
	public function addgroupAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if ($this->getRequest()->isPost()) {
			$group = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('group', '')));
			if ($group === '') {
				echo json_encode(array('exist' => false, 'save' => false)); return;
			}
			$ifExist = $this->_model->selectGroupByName($group);
			if (!empty($ifExist)) {
				echo json_encode(array('exist' => true, 'save' => false)); return;
			}
			$result = (integer) $this->_model->insertGroup($group);
			if ($result > 0) {
				echo json_encode(array('exist' => false,'save' => true, 'id' => $result)); return;
			}
		}
	}

	/**
	 * This function deletes a group. (AJAX)
	 * @return <string> (json)
	 */
	public function deletegroupAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if ($this->getRequest()->isPost()) {
			$id = (integer) $this->getRequest()->getParam('id', 0);
			if ($id === 0) {
				echo json_encode(array('del' => false)); return;
			}
			$result = $this->_model->deleteGroup($id);
			if ($result > 0) {
				echo json_encode(array('del' => true)); return;
			}
		}
	}

	/**
	 * This function returns data about products for shopping. (AJAX)
	 * @return <string>
	 * @deprecated
	 */
	public function productsforautocompleteAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if ($this->getRequest()->isPost()) {
			$products = $this->_model->selectAllProducts();
			$dataProducts = '';
			if (is_array($products) && count($products) > 0) {
				foreach ($products as $product) {
					$dataProducts .= $product['name'] . ':::' . $product['photo'] . ':::' . $product['id'] . ':::' . $product['item_id'] . '###';
				}
			}
			echo $dataProducts; return;
		}
	}

	/**
	 * This function adds new product. (AJAX)
	 * @return string (json)
	 */
	public function addproductAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if ($this->getRequest()->isPost()) {
            /* got variables */
			$name = RCMS_Tools_Tools::stripSlashesIfQuotesOn(trim($this->getRequest()->getParam('name')));
			$itemId = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('item_id')));
			$price = $this->getRequest()->getParam('price');
            $mpn = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('mpn')));
			$weight = $this->getRequest()->getParam('weight');
            $tax = $this->getRequest()->getParam('tax');
			$photo = trim($this->getRequest()->getParam('photo'));
			$brand = strtoupper(trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('brand'))));
			$desc = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('desc')));
			$fullDesc = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('fullDesc')));
			$options = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('options')));
			$related = rtrim($this->getRequest()->getParam('related'), ',');
            $freebies = rtrim($this->getRequest()->getParam('freebies'), ',');
			$groups = explode(',', rtrim($this->getRequest()->getParam('groups'), ','));
            /* create new product */
			$product = new RCMS_Object_Product_Product();
			$product->setName($name);
			$product->setItemId($itemId);
            if((bool)$this->getRequest()->getParam('onsale') != false) {
                $product->setPrice($this->getRequest()->getParam('salePrice'));
				$product->setSaleDue($this->getRequest()->getParam('saleExp'));
				$product->setOldPrice($price);
			}
			else {
                $product->setPrice($price);
			}

			$product->setMpn(($mpn) ? $mpn : '');
			$product->setFullDescription(($fullDesc) ? $fullDesc : '');

            $product->setWeight($weight);
			$product->setPhoto($photo);
			$product->setBrand($brand);
			$product->setDescription($desc);
			$product->setOptions($options);
			$product->setRelated($related);
            $product->setFreebies($freebies);
            $product->setTax($tax);
			$idProduct = $product->save();

			if ($idProduct > 0) {
				$product->setId($idProduct);
				if(isset($groups[0]) && $groups[0]) {
					$product->setGroups($groups);
				}
                /* generate xml file for products */
                $xmlProducts = new RCMS_Object_Product_ProductFeed();
                $xmlProducts->generateFullProductXML();
                /* save page */
				$ifSave = $this->_savePageForProduct($product);
				$pageUrl = $ifSave === true ? preg_replace('/([#@!.:;\'"`$%?&()*|\s\/\\\])/', '-', $product->getName().'-'.$product->getItemId()) : '';
				echo json_encode(array('id' => $idProduct, 'url' => $pageUrl)); return;
			}
			echo json_encode(array('id' => 0)); return;
		}
	}

	/**
	 * This function creates and saves a page for a product.
	 * @param <object> $product
	 * @return <boolean>
	 */
	private function _savePageForProduct(RCMS_Object_Product_Product $product)
    {
        $templateForProduct = $this->_model->selectTemplateByName('product');
        if (!$templateForProduct) {
            $templateForProduct = $this->_model->selectTemplateByName('default');
        }
        $idCategoryProduct = $this->_model->selectCategoryProducts();
		$producCategoryPage = $this->_model->selectProductCategoryPage();
		if(!$producCategoryPage) {
			if(!$idCategoryProduct) {
				$idCategoryProduct = $this->_model->insertCategoryProducts(0, RCMS_Object_QuickConfig_QuickConfig::$productsCategoryName);
			}
			$pageCategory = new RCMS_Object_Page_Page();
            $pageCategory->setH1Tag(RCMS_Object_QuickConfig_QuickConfig::$productsCategoryName);
            $pageCategory->setHeaderTitle(RCMS_Object_QuickConfig_QuickConfig::$productsCategoryName);
            $pageCategory->setUrl(RCMS_Object_QuickConfig_QuickConfig::$productsCategoryUrl);
            $pageCategory->setNavName(RCMS_Object_QuickConfig_QuickConfig::$productsCategoryName);
            $pageCategory->setMetaDescription('');
            $pageCategory->setShortDescription('');
            $pageCategory->setCategoryId($idCategoryProduct);
            $pageCategory->setTemplateId($templateForProduct);
            $pageCategory->setFeaturedId(0);
            $pageCategory->setIs404Page(0);
            $pageCategory->setOrder(100);
            $ownerId = unserialize($this->_session->currentUser)->getId() > 0 ? unserialize($this->_session->currentUser)->getId() : 0;
            $pageCategory->setOwner($ownerId);
            $pageCategory->setSeosambaRuleId(0);
            $pageCategory->setShowInMenu(1);
            $pageCategory->setSiloId(0);
            $pageCategory->setStaticOrder(100);
            $pageCategory->setBestPractices(0);
            $pageCategory->setLastUpdate(date("Y-m-d H:i:s"));
            $pageCategory->setWeight(0);
			$pageCategory->setProtected(0);
			$pageCategory->setMemLandig(0);
			$pageCategory->setProdBrandLand(0);
			$pageCategory->setProdCatLand(0);
            $pageCategory->setTargetedKeyPhrase(RCMS_Object_QuickConfig_QuickConfig::$productsCategoryName);
            $pageCategory->save();
            unset ($pageCategory);
		}

        $pageUrl = preg_replace('/([#@!.:;\'"`$%?&()*|\s\/\\\])/', '-', $product->getName().'-'.$product->getItemId());
        $idCategoryForPage = $this->_model->insertCategoryProducts($idCategoryProduct, $pageUrl);
        $page = new RCMS_Object_Page_Page();
        $page->setH1Tag($pageUrl);
        $page->setHeaderTitle($pageUrl);
        $page->setUrl($pageUrl);
        $page->setNavName($pageUrl);
        $page->setMetaDescription(strip_tags($product->getDescription()));
        $page->setShortDescription(strip_tags($product->getDescription()));
        $page->setCategoryId($idCategoryForPage);
        $page->setTemplateId($templateForProduct);
        $page->setFeaturedId(0);
        $page->setLastUpdate(date("Y-m-d H:i:s", time()));
        $page->setIs404Page(0);
        $page->setOrder(100);
        $ownerId = unserialize($this->_session->currentUser)->getId() > 0 ? unserialize($this->_session->currentUser)->getId() : 0;
        $page->setOwner($ownerId);
        $page->setSeosambaRuleId(0);
        $page->setShowInMenu(1);
        $page->setSiloId(0);
        $page->setStaticOrder(100);
        $page->setBestPractices(0);
        $page->setWeight(0);
		$page->setProtected(0);
		$page->setMemLandig(0);
		$page->setProdBrandLand(0);
		$page->setProdCatLand(0);
        $page->setTargetedKeyPhrase($pageUrl);
        $save = $page->save();
        if ($save !== false) {
            $product->setPageId($save);
            $product->save();
			$this->_saveProductPhotoAsPageTeaser($product->getPhoto(), $product->getPageId(), $page->getUrl());
            $template = new RCMS_Object_Template_Template($templateForProduct);
			if(strtolower($template->getName()) !== 'product') {
				preg_match('/content:(.*)}/', $template->getContent(), $matches);
				if (isset($matches[1])) {
					$this->_saveConatainer($matches[1], $save);
				}
			}
            unset ($template);
            unset ($page);
            return true;
        }
        return false;
	}

	private function _saveProductPhotoAsPageTeaser($productPhotoFullPath, $pageId, $pageUrl) {
		if(!isset($productPhotoFullPath) || !is_string($productPhotoFullPath) || $productPhotoFullPath == '') {
			return false;
		}
		$imgExt = @end(explode('.', end(explode('/', $productPhotoFullPath))));
		$imgName = RCMS_Tools_FilesystemTools::normalize($pageUrl, $pageId) . '.' . $imgExt;
		$pageImageFullPath = 'previews/' . $imgName;
		@copy($productPhotoFullPath, $pageImageFullPath);
		return $this->_model->insertPageImage($pageId, $pageImageFullPath, $imgName);
	}

    /**
     * This function saves a container.
     * @param <string> $name
     * @param <integer> $pageId
     * @return <boolean>
     */
    private function _saveConatainer($name, $pageId)
    {
        $name = trim($name);
        $pageId = (integer)$pageId;
        if ($name == '' || $pageId <= 0) {
            return false;
        }
        $container = new RCMS_Object_Container_Container();
        $container->setType(1);
        $container->setUserId(unserialize($this->_session->currentUser)->getId());
        $container->setPageId($pageId);
        $container->setName($name);
        $container->setPublished(true);
        $container->setIsForSale(true);
        $container->setAllowComments(true);
        $container->setPublishingDate(date('Y-n-d G-i-s'));
        $container->setContent('{$product}');
        $save = $container->save();
        unset ($container);
        if ($save !== false) {
            return true;
        }
        return false;
    }

	/**
	 * This function returns data about a product. (AJAX)
	 * @return <string> (json)
	 */
	public function getdataproductAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if ($this->getRequest()->isPost()) {
			$id = (int) $this->getRequest()->getParam('id');
			$product = new RCMS_Object_Product_Product($id);
			if ($product->getId() > 0) {
				$gr = $product->getGroups();
				$groups = '';
				foreach ($gr as $g) {
					$groups .= $g['id'].',';
				}
                $groups = rtrim($groups, ',');
				$page = new RCMS_Object_Page_Page($product->getPageId());
				$isForSale = ($product->getOldPrice()) ? true : false;
				$data = array(
					'id'        => $product->getId(),
					'name'      => $product->getName(),
					'item_id'   => $product->getItemId(),
					'brand'     => $product->getBrand(),
					'price'     => ($isForSale) ? $product->getOldPrice() : $product->getPrice(),
                    'weight'    => $product->getWeight(),
					'photo'     => $product->getPhoto(),
					'desc'      => $product->getDescription(),
					'options'   => $product->getOptions(),
					'related'   => $product->getRelated(),
                    'freebies'  => $product->getFreebies(),
					'groups'    => $groups,
					'pageurl'   => ($page->getUrl() != null)?$page->getUrl():"",
                    'tax'       => $product->getTax(),
					'salePrice' => ($isForSale) ? $product->getPrice() : '',
					'saleDue'   => ($isForSale) ? $product->getSaleDue() : '',
					'isForSale' => ($isForSale) ? 1 : 0,
					'mpn'       => $product->getMpn(),
					'fullDesc'  => $product->getFullDescription()
				);
                unset ($page);
                unset ($product);
				echo json_encode($data); return;
			}
			echo json_encode(array('id' => 0)); return;
		}
	}

	/**
	 * This function deletes a product. (AJAX)
	 * @return <string> (json)
	 */
	public function deleteproductAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if ($this->getRequest()->isPost()) {
			$id = (int) $this->getRequest()->getParam('id');
			$product = new RCMS_Object_Product_Product($id);
			if ($product->getId() <= 0) {
				echo json_encode(array('del' => false)); return;
			}
			$flagDelete = $product->delete();
			if ($flagDelete) {
                /* generate xml file for products */
                $xmlProducts = new RCMS_Object_Product_ProductFeed();
                $xmlProducts->generateFullProductXML();
				$page = new RCMS_Object_Page_Page($product->getPageId());
				$page->delete();
				echo json_encode(array('del' => true)); return;
			}
			echo json_encode(array('del' => false)); return;
		}
	}

	/**
	 * This function edits a product. (AJAX)
	 * @return <string> (json)
	 */
	public function editproductAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if ($this->getRequest()->isPost()) {
			$id = (int) $this->getRequest()->getParam('id');
			$name = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('name')));
			$itemId = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('item_id')));
			$mpn = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('mpn')));
			$price = $this->getRequest()->getParam('price');
            $weight = $this->getRequest()->getParam('weight');
            $tax = $this->getRequest()->getParam('tax');
			$photo = trim($this->getRequest()->getParam('photo'));
			$brand = strtoupper(trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('brand'))));
			$desc = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('desc')));
			$fullDesc = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('fullDesc')));
			$options = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('options')));
			$related = rtrim($this->getRequest()->getParam('related'), ',');
            $freebies = rtrim($this->getRequest()->getParam('freebies'), ',');
			$groups = explode(',', rtrim($this->getRequest()->getParam('groups'), ','));
			$product = new RCMS_Object_Product_Product($id);
			if ($product->getId() <= 0) {
				echo json_encode(array('save' => false)); return;
			}
			$product->setName($name);
			$product->setItemId($itemId);

			$product->setMpn(($mpn) ? $mpn : '');
			$product->setFullDescription(($fullDesc) ? $fullDesc : '');

			if((bool)$this->getRequest()->getParam('onsale') != false) {
				$product->setPrice($this->getRequest()->getParam('salePrice'));
				$product->setSaleDue($this->getRequest()->getParam('saleExp'));
				$product->setOldPrice($price);
			}
			else {
				$product->setOldPrice(null);
				$product->setSaleDue(null);
				$product->setPrice($price);
			}
            $product->setWeight($weight);
			$product->setPhoto($photo);
			$product->setBrand($brand);
			$product->setDescription($desc);
			$product->setOptions($options);
			$product->setRelated($related);
            $product->setFreebies($freebies);
            $product->setTax($tax);
			$save = $product->save();
			if ($save !== false) {
				$product->setGroups($groups);
                                /* generate xml file for products */
                                $xmlProducts = new RCMS_Object_Product_ProductFeed();
                                $xmlProducts->generateFullProductXML();

								$isExistPage = $this->_model->getPageProductId($id);
								if(!$isExistPage) {
									$ifSave = $this->_savePageForProduct($product);
								}

				echo json_encode(array('save' => true)); return;
			}
			echo json_encode(array('save' => false)); return;
		}
	}

    /**
     * This function returns brands. (AJAX)
     * @return <string> json
     */
    public function getbrandsAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		if ($this->getRequest()->isPost()) {

			$term   = strtolower(trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('term'))));

			$id = 'shopping_brands';
			$brands = $this->_model->selectBrands();

			$return = array();
			if (is_array($brands) && count($brands) > 0) {
				foreach ($brands as $key=>$brand) {
					if (strpos(strtolower($brand), $term) !== false)
						array_push($return, array('id'=>$key, 'label'=>$brand, 'value'=>$brand));
				}
				echo json_encode($return);
			}

		}
	}

    /**
     * This function updates a group.
     * @return <string> (json)
     */
	public function editgroupAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if ($this->getRequest()->isPost()) {
			$id = (integer) $this->getRequest()->getParam('id');
			$name = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('name')));
			if ($name === '' || $id <= 0) {
				echo json_encode(array('save' => false)); return;
			}
			$save = $this->_model->updateGroup($name, $id);
			if ($save !== false) {
				echo json_encode(array('save' => true)); return;
			}
			echo json_encode(array('save' => false)); return;
		}
	}

	public function addtocartAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isPost()) {
			$id = intval($this->getRequest()->getParam('id'));
			$options = $this->getRequest()->getParam('opts');
            $qty = intval($this->getRequest()->getParam('amount'));
			if($options) {
				$itemOptions = array();
				$explodedOpt = explode(',', $options);
				if(sizeof($explodedOpt) > 0) {
					foreach ($explodedOpt as $optionData) {
						$explodedOptData = explode('=', $optionData);
						if(sizeof($explodedOptData) > 0) {
							$itemOptions[$explodedOptData[0]] = $explodedOptData[1];
						}
					}
				}
			}
			$shoppingCart = new RCMS_Object_Shopping_ShoppingCart();
			$shoppingCart->addItem(array(
				'id' => $id,
				'options' => (isset($itemOptions) && is_array($itemOptions)) ? $itemOptions : array() ,
                'qty' => $qty
			));
            $totalPrice = 0;
            $shoppingConfig = $this->_model->selectShoppingConfig();
            if ($shoppingConfig['show-price-ati'] == '1')
                {
                    $taxRule = unserialize($shoppingConfig['default_tax_rule']);
                    if (empty($taxRule)){
                        $rules = unserialize($shoppingConfig['tax-rules']);
                        foreach ($rules as $rule) {
                            if ( ($rule['zone']==$shoppingConfig['country'] && in_array($shoppingConfig['state'],  explode(',', $rule['subzone']))) ||
                                 ($shoppingConfig['state']=='' && in_array($shoppingConfig['country'],explode(',',$rule['subzone']))) )
                            {
                                $taxRule = $rule;
                                break;
                            }
                        }
                    }
                    $totalPrice = $shoppingCart->getTotalPrice(true, $taxRule);
                }
            else
                {
                    $totalPrice = $shoppingCart->getTotalPrice();
                }

			echo json_encode(array('itemsCount' => $shoppingCart->getItemsCountForCart(), 'totalPrice' => round($totalPrice,2)));
		}
	}

	public function viewscAction()
    {
		$this->_helper->viewRenderer->setNoRender(true);
        $shoppingConfig = $this->_model->selectShoppingConfig();
        $shoppingCart = new RCMS_Object_Shopping_ShoppingCart();
		$this->view->products = $shoppingCart->getProductsList();
        $this->view->freebies = $shoppingCart->getFreebiesList();
		$this->view->total = $shoppingCart->getTotalPrice();
		$totalTax = 0;

		$taxableItemsData = $shoppingCart->getTaxableItemsData();

        $shippingData = new RCMS_Object_Shipping_Shipping();
        $shipping = ($shoppingConfig['shipping_type'] != 'pickup' ? $shippingData->getShippingCost() : '0');
        if ($shAddress = $shippingData->getShippingAddress()){
            $location['country'] = $shAddress['country'];
            $location['state'] = $shAddress['state'];
        } else {
            $location['country'] = $shoppingConfig['country'];
            $location['state'] = $shoppingConfig['state'];
        }
        $taxRule = $this->_getTaxRule();
        $taxes = $this->_countTotalTax($shoppingCart->getProductsList(), $taxRule);
        $totalTax = $taxes['total'];
        unset($taxes['total']);
        $itemsTaxes = $taxes;

        $this->view->loggedTitle     = $shoppingConfig['company'] . ' Online Shopping Cart';
        $this->view->currency        = isset($shoppingConfig['currency']) && strlen($shoppingConfig['currency']) == 3 ? $shoppingConfig['currency'] : '';
        $this->view->config          = $shoppingConfig;
        $this->view->settingsPayPal  = unserialize($shoppingConfig['paypal']);
        $this->view->logoPath        = $this->getWebSiteUrl();
        $this->view->companyLogoName = $shoppingConfig['company_logo'];
        $this->view->companyName     = $shoppingConfig['company'];
        $this->view->companyEmail    = $shoppingConfig['email'];
        $this->view->companyPhone    = $shoppingConfig['phone'];
        $this->view->totalTax        = number_format($totalTax,2,'.','');
        $this->view->totalPrice      = number_format($shoppingCart->getTotalPrice() + $totalTax + $shipping,2,'.','');
        $this->view->taxPerItems     = isset($itemsTaxes) && !empty($itemsTaxes) ? $itemsTaxes : null;
        $this->view->location        = isset($location) ? $location : null;
        $this->view->companyAddress  = $shoppingConfig['address'];
        $this->view->keepShoppingUrl = $this->_session->lastUrl;
        $this->view->policyUrl       = $shoppingConfig['policy_page_url'];
        $this->view->shippingGeneral = unserialize($shoppingConfig['shipping_general']);
        $this->view->allowShipping   = ($shoppingConfig['shipping_type'] != 'pickup' ? true : false);
        $this->view->shipping        = number_format($shipping,2,'.','');
        $this->view->shippingData    = ($shoppingConfig['shipping_type'] != 'pickup' ? $shippingData->getShippingAddress() : null);
        $this->view->shippingService = ($shoppingConfig['shipping_type'] == 'external' ? 'external' : 'internal');
		$this->view->useHttps = $shoppingConfig['use_https'];
		$page = $this->view->render($this->getViewScript());
		$parser = new RCMS_Object_Parser_Parser($page, '', $this->_session->isLogged);
		$content = $parser->processContent();
        echo $this->_translator->processScreen($content);
		}
		
	private function _countTotalTax($cartData, $taxRule) {
		$tax = array('total'=>0);
        foreach($cartData as $item) {
            $tax[$item['id']] = round(($item['price']*$taxRule['tax'][$item['taxable']]/100), 2);
            $tax['total'] += $tax[$item['id']]*$item['count'];
		}
        $tax['total'] = number_format($tax['total'],2,'.','');
        return $tax;
	}

	public function recountAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$toRemove   = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('toremove')));
		$toRecount  = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('torecount')));
		$options    = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('options')));
		$remOptions = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('remOptions')));
		$shoppingCart = new RCMS_Object_Shopping_ShoppingCart();
        $items = $shoppingCart->getItems();
		if(!empty($toRemove)) {
			$remOptions = $this->_makeOptions($remOptions);
			$shoppingCart->removeItem($toRemove, $remOptions);
		}

		if(!empty ($toRecount)) {
			$options = $this->_makeOptions($options);
            $id = (int) $toRecount->id;
            $qty = (int) $toRecount->qty;
            if ($qty != 0) {
                $shoppingCart->setItemQuantity($id, $qty, $options);
            } else {
                $shoppingCart->removeItem($id, $options);
            }
		}
        echo json_encode(array('itemsCount' => $shoppingCart->getItemsCount(),'totalPrice' => $shoppingCart->getTotalPrice()));
	}

	private function _makeOptions($options) {
		if (is_array($options)){
            $rightOpts = array();
            foreach ($options as $optString) {
                $explodedOpt = explode('=', $optString);
                //$explodedOptVals = explode('=', $explodedOptString[1]);
                $rightOpts[$explodedOpt[0]] = $explodedOpt[1];
            }
            return $rightOpts;
        }
        return false;
	}

	public function sendEmail($to, $toComment, $from, $fromComment, $subject, $body, $useSmtp, $attachment = null) {
		$mail = new RCMS_Object_Mailer_Mailer();
		if($useSmtp) {
			$mail->setSmtpConfig($this->_smtpLogin, $this->_smtpPassword, $this->_smtpHost);
			$mail->setTransport(RCMS_Object_Mailer_Mailer::MAIL_TYPE_SMTP);
		}
		$mail->setFrom($fromComment);
		$mail->setFromMail($from);
		$mail->setTo($toComment);
		$mail->setToMail($to);
		$mail->setSubject($subject);
        $mail->setBody($body);
        if (null !== $attachment) $mail->createAttachment($attachment);
		try {
			$result = $mail->send();
		} catch (Exception $e){
			error_log($e->getFile().' (line '.$e->getLine().'): '.$e->getMessage());
			$result = false;
		}
		return $result;
	}

	private function _checkSmtpAllowedInConfig() {
		if(isset($this->_configTableArray['use_smtp']) && $this->_configTableArray['use_smtp'] == 1 &&
			isset($this->_configTableArray['smtp_login']) && $this->_configTableArray['smtp_login'] != '' &&
			isset($this->_configTableArray['smtp_password']) && $this->_configTableArray['smtp_password'] != '') {
			return true;
		}
		return false;
	}

	private function _initSmtp() {
		$this->_domain = ($this->_smtpHost)? ucfirst($this->_smtpHost) : $this->_websiteUrl;
		$configArray = $this->_model->selectAllConfigSettings();
		if($configArray) {
			$this->_configTableArray = $configArray;
			if(isset($configArray['smtp_host']) && $configArray['smtp_host'] != '') {
				$this->_smtpHost = $configArray['smtp_host'];
			}
			if(isset($configArray['smtp_login']) && $configArray['smtp_login'] != '') {
				$this->_smtpLogin = $configArray['smtp_login'];
			}
			if(isset($configArray['smtp_password']) && $configArray['smtp_password'] != '') {
				$this->_smtpPassword = $configArray['smtp_password'];
			}

			$this->_smtpConfigArray = array(
				'auth'      => 'login',
				'username'  => $this->_smtpLogin,
				'password'  => $this->_smtpPassword,
				'host'      => $this->_smtpHost
			);
		}
	}

	private function validateCaptcha($captchaInput,$captchaId) {
		$captchaSession = new Zend_Session_Namespace('Zend_Form_Captcha_' . $captchaId);
		$captchaIterator = $captchaSession->getIterator();
		$captchaWord = (isset($captchaIterator['word'])? $captchaIterator['word']:'');
		if( $captchaWord ) {
			if( $captchaInput != $captchaWord ) {
				return false;
			} else {
				return true;
			}
		} else {
			return false;
		}
	}

    public function quotemeAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $generator = new RCMS_Object_Generator_Generator();
        $shoppingConfig = $this->_model->selectShoppingConfig();
        $configArray = $this->_model->selectAllConfigSettings();

        if ($this->getRequest()->isPost()) {
			if( $this->getRequest()->getParam('captcha', false) ) {
				$captchaInput = $this->getRequest()->getParam('captcha');
				$captchaId = $this->getRequest()->getParam('captchaId');

				if( !$this->validateCaptcha($captchaInput,$captchaId) ) {
					echo json_encode(array('done' => false, 'captchaNewId' => RCMS_Tools_Tools::generateCaptcha()));
					return false;
				}
			}
            $formData =  $this->getRequest()->getParams();
            $userName = $formData['name'];
            $userEmail = $formData['email'];

            if ($shoppingConfig['autoquote'] || (isset($formData['autoquote']) && $formData['autoquote'] == true)) {
                /* handling automatic quote generation */
                $noShipping = (isset($formData['noshipping']) && $formData['noshipping'] == true) ? true : false;
                $newId = $this->_generateQuote($formData, $noShipping);
                if ($newId) {
                    $quoteUrl = $this->getWebSiteUrl().'sys/backend_quote/preview/qid/'.$newId.'.'.md5($newId).'.'.$newId;
                    $quote = new RCMS_Object_Quote_Quote($newId);
                    $userCart = new RCMS_Object_Shopping_ShoppingUserCart($quote->getShoppingCartId());
                    $tax = $this->_countTotalTax($userCart->getCartData(), $this->_getTaxRule());
                    $quote->setContent($generator->generateQuoteContent($quote, $userCart, $tax));
                    $subject = $shoppingConfig['quote_email_subj'];
                    $body = !empty($shoppingConfig['quote_email_body']) ? $shoppingConfig['quote_email_body'] : $generator->generateQuoteMailToUser($newId);
                    $body = str_replace('{$name}', $formData['name'], $body);
                    $body = str_replace('{$date}', date('Y-m-d'), $body);
                    $body = str_replace('{$quote_url}', $quoteUrl, $body);
                    $body = str_replace('{$website_url}', $this->getWebSiteUrl(), $body);
                    $body = str_replace('{$logged_user}', '<a href="mailto:'.$shoppingConfig['email'].'">'.$shoppingConfig['email'].'</a>', $body);
                    $useSmtp = $this->_checkSmtpAllowedInConfig();
					$this->sendEmail($shoppingConfig['email'], $shoppingConfig['company'], $this->_configTableArray['admin_email'], '', 'A new quote #'.$newId.' request on '.$this->getWebSiteUrl() , $generator->generateQuoteMailToAdmin($formData, $newId), $useSmtp);
                    $status = $this->sendEmail($formData['email'], $formData['name'], $shoppingConfig['email'], $shoppingConfig['company'], $subject, $body, $useSmtp);
					if ($status) $quote->setStatus(RCMS_Object_Quote_Quote::Q_STATUS_SENT);
                    $quote->save();
                    unset($quote);
					echo json_encode($status ? array('done' => true,'redirect' =>$shoppingConfig['autoquote']?$quoteUrl:'') : array('done' => false));
					return;
                }
            } else {
                /* get smtp settings */
                $useSmtpInConfig = $this->_checkSmtpAllowedInConfig();

                if ($useSmtpInConfig) {
                    $useSmtp = true;
                } else {
                    $useSmtp = false;
                }

                /* send email to admin from shopping table */
                $subject = 'A new quote #'.$newId.' request on '.$this->getWebSiteUrl();
                $body = $generator->generateQuoteMailToAdmin($formData);
                $flag = $this->sendEmail($shoppingConfig['email'], $shoppingConfig['company'], $this->_configTableArray['admin_email'], '', $subject, $body, $useSmtp);

                /* send email to client */
                $body = $shoppingConfig['quote_responder_body'];
                $body = str_replace('{$name}', $userName, $body);
                $flag = $this->sendEmail($userEmail, '', $shoppingConfig['email'], $shoppingConfig['company'], $shoppingConfig['quote_responder_subj'], $body, $useSmtp);
                /*saving cart and put a new quote */
                if ($flag) {
                    $this->_generateQuote($formData);
                    echo json_encode(array('done' => true)); return;
                }
                echo json_encode(array('done' => false)); return;
            }
            echo json_encode(array('done' => false)); return;
		}
    }

    /**
     * This handler for paypal account. (AJAX)
     */
    public function handlerpaypalaccountAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

        $shoppingConfig = $this->_model->selectShoppingConfig();
		$generator = new RCMS_Object_Generator_Generator();

        if ($this->getRequest()->isPost()) {
            $data =  $this->getRequest()->getParams();

            if ($data['payment_type'] == 'instant') {
                unset ($data['controller']);
                unset ($data['action']);
                unset ($data['module']);
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, 'https://www.paypal.com/cgi-bin/webscr');
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_VERBOSE, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array_merge(array('cmd'=>'_notify-validate'), $data)));
                $response = curl_exec($ch);
                curl_close($ch);

                if ($response == 'VERIFIED') {
                    $dataPayment = array(
                        'transaction_id'    =>  $data['txn_id'],
                        'amount'            =>  $data['mc_gross'],
                        'payer_id'          =>  $data['payer_id'],
                        'description'       =>  $data['custom'],
                        'billing_name'      =>  $data['address_name'],
                        'billing_email'     =>  $data['payer_email'],
                        'billing_address'   =>  $data['address_street'],
                        'billing_address1'  =>  $data['address_street'],
                        'billing_country'   =>  $data['address_country'],
                        'billing_city'      =>  $data['address_city'],
                        'billing_state'     =>  $data['address_state'],
                        'billing_zip'       =>  $data['address_zip'],
                        'date'              =>  date('Y-n-d G-i-s'),
                        'sc_id'             =>  '0'
                    );
                    $this->_model->insertShoppingPayPalPayment($dataPayment);

                    /* sending email to store admin */
                    $useSmtp = $this->_checkSmtpAllowedInConfig();
                    $subject = 'You received a new order on ' . $this->getWebSiteUrl();
                    $body  = $generator->generatePaymentNoticeEmail($dataPayment, $shippingData);
                    $this->sendEmail($shoppingConfig['email'], '', $this->_configTableArray['admin_email'], 'Store System Email', $subject, $body, $useSmtp);
                }
            }
        }
    }

    /**
     * This handler for credit cart using the service of paypal. (AJAX)
     * @return <string> (json)
     */
	public function handlerpaypalcreditcardAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$shoppingCart = new RCMS_Object_Shopping_ShoppingCart();
		$cartCount = $shoppingCart->getItemsCount();
		if($cartCount == 0){
			echo json_encode(array('done'=> false,'state'=>'expired'));
			return;
		}

        $generator = new RCMS_Object_Generator_Generator();

        $shoppingConfig = $this->_model->selectShoppingConfig();

        if ($this->getRequest()->isPost()) {
            $data =  $this->getRequest()->getParams();

            $dataForPayment = array(
                'PAYMENTACTION'     =>  'Sale',
                'IPADDRESS'         =>  $_SERVER['REMOTE_ADDR'],
                'CREDITCARDTYPE'    =>  $data['type'],
                'ACCT'              =>  trim($data['cardnumber']),
                'EXPDATE'           =>  str_pad($data['expiration_date_month'], 2, '0', STR_PAD_LEFT).$data['expiration_date_year'],
                'CVV2'              =>  trim($data['verification_number']),
                'EMAIL'             =>  trim($data['email']),
                'FIRSTNAME'         =>  trim($data['firstname']),
                'LASTNAME'          =>  trim($data['lastname']),
                'STREET'            =>  trim($data['billing_address1']),
                'STREET2'           =>  trim($data['billing_address2']),
                'CITY'              =>  trim($data['city']),
                'STATE'             =>  $data['state'],
                'COUNTRYCODE'       =>  $data['country'],
                'ZIP'               =>  trim($data['zip']),
                'PHONENUM'          =>  trim($data['phone']),
                'AMT'               =>  $data['amt'],
				'ITEMAMT'			=> ($data['amt']-$data['tax']-$data['shipping']),
				'SHIPPINGAMT'		=>  $data['shipping'] !== '' ? $data['shipping'] : '0.00',
                'TAXAMT'			=>	$data['tax'] !== '' ? $data['tax'] : '0.00',
                'CURRENCYCODE'      =>  $data['currency_code'],
                'DESC'              =>  $data['desc']
            ); // + ($data['tax'] !== '' ? $data['tax'] : '0') + ($data['shipping'] !== '' ? $data['shipping'] : '0')

            $shipping = new RCMS_Object_Shipping_Shipping();

            if ($shoppingConfig['shipping_type'] != 'pickup' ){
                $shippingAddress = $shipping->getShippingAddress();
                $dataForPayment = $dataForPayment + array(
                    'SHIPTONAME'     => $shippingAddress['firstname'] . ' ' . $shippingAddress['lastname'],
                    'SHIPTOSTREET'   => $shippingAddress['address1'],
                    'SHIPTOSTREET2'  => $shippingAddress['address2'],
                    'SHIPTOCITY'     => $shippingAddress['city'],
                    'SHIPTOSTATE'    => $shippingAddress['state'],
                    'SHIPTOZIP'      => $shippingAddress['zip'],
                    'SHIPTOCOUNTRY'  => $shippingAddress['country'],
                    'SHIPTOPHONENUM' => $shippingAddress['phone']
                );
            }

            $objPayPal = new RCMS_Object_PayPal_PayPal();
            $payment = $objPayPal->createDoDirectPayment($dataForPayment);

            if (preg_match('/success/i', $payment['ACK']) && isset($payment['TRANSACTIONID'])) {
                $infoPayment = $objPayPal->getTransactionDetails($payment['TRANSACTIONID']);

                if (preg_match('/success/i', $infoPayment['ACK'])) {
                    /* load session based cart */
                    //$shoppingCart = new RCMS_Object_Shopping_ShoppingCart();

                    /* create and save cart for current user */
                    $userCart = new RCMS_Object_Shopping_ShoppingUserCart();
                    $userCart->setName(trim($data['firstname']).' '.trim($data['lastname']));
                    $userCart->setEmail(trim($data['email']));
                    $userCart->setCompany('');
                    $userCart->setAddress1(trim($data['billing_address1']));
                    $userCart->setAddress2(trim($data['billing_address2']));
                    $userCart->setCity(trim($data['city']));
                    $userCart->setCountry($data['country']);
                    $userCart->setState($data['state']);
                    $userCart->setZip(trim($data['zip']));
                    $userCart->setPhone(trim($data['phone']));
                    $userCart->setComments('Paypal Transaction ID: '.$infoPayment['TRANSACTIONID']);
                    $userCart->setCartData($shoppingCart->getProductsList());
                    $newCartId = $userCart->save();

                    /* saving shipping data */
                    if ($shoppingConfig['shipping_type'] != 'pickup'){
                        $shipping->setCartId($newCartId);
                        $shipping->saveShipping();
                    }

                    /* saving payment details*/
                    $dataPayment = array(
                        'transaction_id'    =>  $infoPayment['TRANSACTIONID'],
                        'amount'            =>  $infoPayment['AMT'],
                        'payer_id'          =>  $infoPayment['PAYERID'],
                        'description'       =>  $data['desc'],
                        'billing_name'      =>  trim($data['firstname']).' '.trim($data['lastname']),
                        'billing_email'     =>  (isset($infoPayment['EMAIL'])?$infoPayment['EMAIL']:''),
                        'billing_address'   =>  trim($data['billing_address1']),
                        'billing_address1'  =>  trim($data['billing_address2']),
                        'billing_country'   =>  $data['country'],
                        'billing_city'      =>  trim($data['city']),
                        'billing_state'     =>  $data['state'],
                        'billing_zip'       =>  trim($data['zip']),
                        'date'              =>  date('Y-n-d G-i-s'),
                        'sc_id'             =>  $newCartId
                    );
                    $this->_model->insertShoppingPayPalPayment($dataPayment);

					$goodsPrice = 0;
					$products = $shoppingCart->getProductsList();
					foreach ($products as $prod) {
						$goodsPrice = $goodsPrice + (($prod['price'])*($prod['count']));
					}

					$shippingPrice = 0;
					$shippingType = '-';
					if($shoppingConfig['shipping_type'] != 'pickup') {
						$shippingPrice = ($data['amt']*1)-($goodsPrice*1)-($data['tax']*1);
						$shippingType = $shipping->getShippingType();
						$shippingType = explode('|', $shippingType);
					}

					$this->view->billingInfo = array(
						"First Name"=>trim($data['firstname']),
						"Last Name"=>trim($data['lastname']),
						"E-mail"=>trim($data['email']),
						"Company"=>'-',
						"Address 1"=>trim($data['billing_address1']),
						"Address 2"=>trim($data['billing_address2']),
						"Country"=>trim($data['country']),
						"City"=>trim($data['city']),
						"State"=>trim($data['state']),
						"Zip"=>$data['zip'],
						"Phone"=>trim($data['phone'])
					);

					$this->view->shippingInfo = array(
						"First Name"=>isset($shippingAddress)?$shippingAddress['firstname']:'-',
						"Last Name"=>isset($shippingAddress)?$shippingAddress['lastname']:'-',
						"E-mail"=>isset($shippingAddress)?$shippingAddress['email']:trim($data['email']),
						"Company"=>isset($shippingAddress)?$shippingAddress['company']:'-',
						"Address 1"=>isset($shippingAddress)?$shippingAddress['address1']:'-',
						"Address 2"=>isset($shippingAddress)?$shippingAddress['address2']:'-',
						"Country"=>isset($shippingAddress)?$shippingAddress['country']:'-',
						"City"=>isset($shippingAddress)?$shippingAddress['city']:'-',
						"State"=>isset($shippingAddress)?$shippingAddress['state']:'-',
						"Zip"=>isset($shippingAddress)?$shippingAddress['zip']:'-',
						"Phone"=>isset($shippingAddress)?$shippingAddress['phone']:'-',
						"Shipping type"=>isset($shippingAddress)?$shippingType['2']:'-',
						"Shipping instructions"=>isset($shippingAddress)?$shippingAddress['instructions']:'-'
					);

					$filePath = Zend_Registry::get('config');
					$filePath = unserialize($filePath);
					$filePath = $filePath->website->website->path;
					$imgfile = $filePath.$shoppingConfig['company_logo'];
					$this->view->merchant = $this->_config->website->website->url;
					$this->view->invoiceNum = $infoPayment['PAYERID'];
					$this->view->businessName = $shoppingConfig['company'];
					$this->view->businessPhone = $shoppingConfig['phone'];
					$this->view->businessEmail = $shoppingConfig['email'];
					$this->view->businessAddr1 = $shoppingConfig['address'];
					$this->view->businessAddr2 = $shoppingConfig['address2'];
					$this->view->businessCity = $shoppingConfig['city'];
					$this->view->businessState = $shoppingConfig['state'];
					$this->view->businessZip = $shoppingConfig['zip'];
					$this->view->businessCountry = $shoppingConfig['country'];
					$this->view->policy = $shoppingConfig['policy_page_url'];
					$this->view->legal = $shoppingConfig['legal-info'];
					$this->view->subtotal = number_format($goodsPrice,2);
					$this->view->tax = number_format($data['tax'],2);
					$this->view->shipping = number_format($shippingPrice,2);
					$this->view->amount = number_format($data['amt'],2);
					$this->view->currency = $shoppingConfig['currency'];
					$this->view->products = $products;
					$this->view->dateTxn = date('Y-n-d G-i-s');
					$this->view->txn = $infoPayment['TRANSACTIONID'];
					$this->view->referrer = $this->_session->userReferrerUrl;
					$this->view->keywords = $this->getSearchEngineKeyWords($this->_session->userReferrerUrl);

					$useSmtp = $this->_checkSmtpAllowedInConfig();
					$this->view->toAdmin = true;
                    $subject = 'You received a new order on '.$this->_config->website->website->url;
                    $body  = $this->_translator->processScreen($this->view->render("generator/paypalmailreport.phtml"));
					//$generator->generatePaymentNoticeEmail($dataPayment, $shipping);
                    $this->sendEmail($shoppingConfig['email'], '', $this->_configTableArray['admin_email'], 'Store System Email', $subject, $body, $useSmtp);
					$this->view->toAdmin = false;
					$subject = 'Your order on '.$this->_config->website->website->url;
					$body = $this->view->render("generator/paypalmailreport.phtml");
					$mail = $this->sendEmail(trim($data['email']), '', $this->_configTableArray['admin_email'], 'Store System Email', $subject, $body, $useSmtp, $imgfile);

                    echo json_encode(array('done' => true)); return;
                }
                echo json_encode(array('done' => false)); return;
            }
            echo json_encode(array('done' => false)); return;
        }
    }

    /**
     *  internal function uses for validating shipping config data
     */
    private function _validateShippingData($item, $key) {
        if (!preg_match('/^(\d+(\.\d+)?)?$/', $item)) {
            array_push($this->_error,$key);
        }
    }

    /**
     * Action to count shipping according to shipping data in config
     * @return void
     * @deprecated
     */
    public function countshippingAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if ($this->getRequest()->isPost()){
            $shippingTotal = 0;
            $shoppingConfig  = $this->_model->selectShoppingConfig();
            $shippingGeneral = unserialize($shoppingConfig['shipping_general']);
            $shoppingCart    = new RCMS_Object_Shopping_ShoppingCart();

            $userData = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('shipping_data')));
            if (trim($userData->country) == '') {
                $this->_session->shipping = array ('type' => 'no data', 'total'=> 0);
                echo $this->_session->shipping;
                return;
            }

            switch ($shoppingConfig['shipping_type']) {
                case 'pickup':
                    $this->_session->shipping = array ('type' => 'pickup', 'total'=> 0);
                    echo $this->_session->shipping;
                    return;
                    break;

                case 'amount':
                    $shippingAmount = unserialize($shoppingConfig['shipping_amount']);
                    $shippingType = ($userData->country == $shoppingConfig['country'] ? 'national' : 'international');
                    $amount = $shoppingCart->getTotalPrice();

                    switch ($amount){

                        case ($amount < $shippingAmount[1]['limit']):
                            $shippingTotal = $shippingAmount[1][$shippingType];
                            break;

                        case ($amount < $shippingAmount[2]['limit']):
                            $shippingTotal = $shippingAmount[2][$shippingType];
                            break;

                        case ($amount > $shippingAmount[3]['limit']):
                            $shippingTotal = $shippingAmount[3][$shippingType];
                            if ($amount > $shippingGeneral['free-shipping-over']){
                                if ($shippingGeneral['free-shipping-options'] == $shippingType) {
                                    $shippingTotal = '0';
                                } else if ($shippingGeneral['free-shipping-options'] == 'both') {
                                    $shippingTotal = '0';
                                }
                            }
                            break;

                        default:
                            break;
                    }
                    break;

                case 'weight':
                    $shippingWeight = unserialize($shoppingConfig['shipping_weight']);
                    $shippingType = ($userData->country == $shoppingConfig['country'] ? 'national' : 'international');
                    $weight = $shoppingCart->getTotalWeight();
                    switch ($weight){
                        case ($weight < $shippingWeight[1]['limit']):
                            $shippingTotal = $shippingWeight[1][$shippingType];
                            break;
                        case ($weight < $shippingWeight[2]['limit']):
                            $shippingTotal = $shippingWeight[2][$shippingType];
                            break;
                        case ($weight > $shippingWeight[3]['limit']):
                            $shippingTotal = $shippingWeight[3][$shippingType];
                            break;
                    }
                    break;
                default:
                    return false;
                    break;
            }

        }
        $this->_session->shipping = array ('type' => $shippingType, 'total'=> $shippingTotal);
        $this->_session->shippingData = $userData;

        echo json_encode($this->_session->shipping);
        return;

    }

    /**
     * Method loads taxes configuration screen
     */
    public function taxesAction() {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        $this->_error = array();

        $shoppingConfig = $this->_model->selectShoppingConfig();

        if ($this->getRequest()->isPost()){
            $taxrules      = $this->getRequest()->getParam('taxrule');
            $defaultRuleId = $this->getRequest()->getParam('defaultRuleId');
            $displayATI    = $this->getRequest()->getParam('display-ATI');

            foreach ($taxrules as $num => $rule) {
                if (strlen(trim(implode('',$rule['tax']))) == '0') {
                    unset($taxrules[$num]);
                    continue;
                }
                if ($rule['zone'] != 'pickup' && (strlen(trim($rule['subzone'])) == '0' || trim($rule['subzone']) == 'click to select' ) ){
                    unset($taxrules[$num]);
                }
                foreach ($rule['tax'] as $key => &$value) {
                    if (!is_numeric($value)) {
                        array_push ($this->_error, $value);
                    }
                }
            }

            if (count($this->_error)){
                $this->view->update = false;
                $this->view->error = true;
            } else {
                if (is_array($defaultRuleId)){
                    $defaultRuleId = $taxrules[$defaultRuleId[0]];
                    $this->_model->updateShoppingConfig('default_tax_rule', serialize($defaultRuleId));
                } else {
                    $this->_model->updateShoppingConfig('default_tax_rule', serialize(array()));
                }

                $data   = serialize($taxrules);
                $labels = serialize(array_merge(array('0'=>'non taxable'),$this->getRequest()->getParam('label')));

                $this->_model->updateShoppingConfig('tax-rules', $data);
                $this->_model->updateShoppingConfig('tax-labels', $labels);
                $this->_model->updateShoppingConfig('show-price-ati', $displayATI?$displayATI:0);
                $this->view->update = true;
                $this->view->error = false;
                $shoppingConfig = $this->_model->selectShoppingConfig();
            }
        }
        $this->view->taxrules       = unserialize($this->_model->selectTaxRules());
        $this->view->labels         = unserialize($this->_model->selectTaxLabels());
        $defaultRule                = unserialize($shoppingConfig['default_tax_rule']);
        $this->view->defaultRuleId  = $defaultRule['id'];
        $this->view->displayATI     = (bool) $shoppingConfig['show-price-ati'];
        echo $this->_translator->processScreen($this->view->render($this->getViewScript()));
    }

    /**
     * Calculating total tax for the cart (AJAX)
     *
     */
    public function counttaxAction() {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        $totalTax = 0;

        if ($this->getRequest()->isPost()){

            $userCountry = trim($this->getRequest()->getParam('userCountry'));
            $userState   = trim($this->getRequest()->getParam('userState'));

            $shoppingCart = new RCMS_Object_Shopping_ShoppingCart();

            $tax = $this->_countTotalTax($shoppingCart->getProductsList(), $this->_getTaxRule(array('country'=>$userCountry, 'state'=>$userState)));
            $totalTax = $tax['total'];
            unset($tax['total']);
        }

        echo json_encode(array('totaltax' => $totalTax, 'taxPerItem' => $tax));
    }

    private function _generateQuote(array $userinfo, $withoutShipping = false){
        $shoppingConfig = $this->_model->selectShoppingConfig();
        $configArray = $this->_model->selectAllConfigSettings();

        if (!empty($userinfo)) {
            /* load session based cart */
            $shoppingCart = new RCMS_Object_Shopping_ShoppingCart();
            /* create and save cart for current user */
            $userCart = new RCMS_Object_Shopping_ShoppingUserCart();
            $userCart->setName($userinfo['name']);
            $userCart->setEmail($userinfo['email']);
            $userCart->setCompany($userinfo['company']);
            $userCart->setAddress1($userinfo['address1']);
            $userCart->setAddress2($userinfo['address2']);
            $userCart->setCity($userinfo['city']);
            $userCart->setCountry($userinfo['country']);
            $userCart->setState($userinfo['state']);
            $userCart->setZip($userinfo['zip']);
            $userCart->setPhone($userinfo['phone']);
            $userCart->setComments(strip_tags($userinfo['comments']));
            $userCart->setCartData($shoppingCart->getProductsList(), $shoppingCart->getFreebiesList());
            $newCartId = $userCart->save();
            /* creating new quote */
            $quote = new RCMS_Object_Quote_Quote();
            $quote->setShoppingCartId($newCartId);
            $quote->setName($userinfo['name']);
            $quote->setStatus(RCMS_Object_Quote_Quote::Q_STATUS_NEW);
            $quote->setInternalMessage(strip_tags($userinfo['comments']));
            $quote->setLastEditedBy('Auto');
            $quote->setValidUntilDate(date('Y-m-d H:i:s',time()+3*24*60*60));
            $id = $quote->save();
            unset($quote);

            /* saving shipping address */
            if ($shoppingConfig['shipping_type'] != 'pickup' && $withoutShipping === false){
                $shippingData = new RCMS_Object_Shipping_Shipping();
                $shippingData->setCartId($newCartId);
                $shippingData->saveShipping();
            } else {
                $shippingData = new RCMS_Object_Shipping_Shipping();
                $shippingData->setShippingCost('0.00');
                $shippingData->setShippingService(array('type'=>'Quote manual', 'price' => '0.00'));
                $userinfo['firstname'] = $userinfo['name'];
                $userinfo['lastname'] = '';
                unset($userinfo['controller']);
                unset($userinfo['action']);
                unset($userinfo['model']);
                $shippingData->setShippingAddress($userinfo);
                $shippingData->setCartId($newCartId);
                $shippingData->saveShipping();
            }

            return ($id ? $id : false);
        }

        return false;
    }

    public function rateproductAction(){
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if ($this->getRequest()->isPost()){
            $productId  = (int) $this->getRequest()->getParam('productId');
            $rating     = (int) $this->getRequest()->getParam('rating');
            if (!isset($this->_session->ratedProducts)){
                $this->_session->ratedProducts = array();
            }
            if (in_array($productId, $this->_session->ratedProducts)){
                echo json_encode(array('done' => 'cancel'));
                return;
            } else {
                $product = new RCMS_Object_Product_Product($productId);
                if ($product->saveRating($rating)) {
                    echo json_encode(array(
                        'done'=>true,
                        'rating' => $product->getRatingFormatted(),
                        'totalvotes' => $product->getTotalVotes()
                            ));
                    array_push($this->_session->ratedProducts, $productId);
                    return;
                }
            }
        }

        echo json_encode(array('done' => false));
    }

    public function saveuserdataAction(){
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if ($this->getRequest()->isPost()){
			$shoppingConfig = $this->_model->selectShoppingConfig();
			$shoppingCart = new RCMS_Object_Shopping_ShoppingCart();
			$userCart = new RCMS_Object_Shopping_ShoppingUserCart();
			if($shoppingConfig['shipping_type'] == 'pickup') {
				$userCart->setCartData($shoppingCart->getProductsList(), $shoppingCart->getFreebiesList());
				$userCartId = $userCart->save();
			}
			else {
				$shipping = new RCMS_Object_Shipping_Shipping();
				$address  = $shipping->getShippingAddress();
				$userCart->setName($address['firstname'] . $address['lastname']);
				$userCart->setEmail($address['email']);
				$userCart->setCompany('');
				$userCart->setAddress1($address['address1']);
				$userCart->setAddress2($address['address2']);
				$userCart->setCity($address['city']);
				$userCart->setState($address['state']);
				$userCart->setZip($address['zip']);
				$userCart->setCountry($address[country]);
				$userCart->setPhone($address['phone']);
				$userCart->setComments('');
				$userCart->setCartData($shoppingCart->getProductsList(), $shoppingCart->getFreebiesList());
				$userCartId = $userCart->save();
				$shipping->setCartId($userCartId);
				$shipping->saveShipping();
			}
        }

        echo json_encode(array('done'=>true, 'reference' => 'cart_'.$userCartId));
    }

    private function _getTaxRule ( $location = null ){
        $shoppingConfig = $this->_model->selectShoppingConfig();

        $taxRules = unserialize($shoppingConfig['tax-rules']);

		if ($taxRules) {
			if ($shoppingConfig['shipping_type'] == 'pickup'){
				foreach ($taxRules as $rule) {
					if (in_array('pickup',$rule)){
						return $rule;
					}
				}
			} else {
				if ($location === null ){
					$shippingData = new RCMS_Object_Shipping_Shipping();
					$sAddress = $shippingData->getShippingAddress();
					if (!empty($sAddress)){
						$location['country'] = $sAddress['country'];
						$location['state'] = $sAddress['state'];
					} else {
						$location['country'] = $shoppingConfig['country'];
						$location['state'] = $shoppingConfig['state'];
					}
				}
			}

			foreach ($taxRules as $rule) {
				if (($rule['zone'] == $location['country'] && $location['state'] != '' && strpos($rule['subzone'],$location['state'])!==false)
					 || ((empty($location['state']) || $location['state'] == 'null') && strpos($rule['subzone'],$location['country']) !== false)  ) {

					return $rule;
				}
			}
		}
        return false;
    }

	/**
	 * Return a list of products matched with part of name or ids. (AJAX)
	 * @method GET
	 * @return <string> json
	 */
	public function getproductsAction(){
		$this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

		$return		= array();
		$term		= strtolower(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('term')));
		$ids		= RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('ids'));

		if ($ids) {
			$ids = explode(',', $ids);
			foreach ($ids as $id){
				if ($id > 0){
					$product = new RCMS_Object_Product_Product($id);
					array_push($return, array(
						'value'			=> $product->getId(),
						'sku'			=> $product->getItemId(),
						'label'			=> $product->getName(),
						'desc'			=> $product->getDescription(),
						'price'			=> $product->getPrice(),
						'img'			=> $product->getPhoto()
					));
					unset($product);
				}
			}
		} elseif ($term) {
			$products = $this->_model->findProducts($term);
			foreach ($products as $product) {
				array_push($return, array(
					'value'			=> $product['id'],
					'sku'			=> $product['item_id'],
					'label'			=> $product['name'],
					'desc'			=> $product['desc'],
					'price'			=> $product['price'],
					'img'			=> $product['photo']
				));
			}
		}
		echo json_encode($return);
	}

	public function getSearchEngineKeyWords($urlEngine) {
		$keyWords = null;
		$urlParts = parse_url($urlEngine);
		$query = (isset($urlParts['query']))? $urlParts['query']:
				 (isset($urlParts['fragment']) ? $urlParts['fragment']:
				 '');
	    if($query=='' || !$query) {
	        $keyWords = ' ';
			return $keyWords;
	    }
		else {
			parse_str($query, $queryParts);
			if(isset($queryParts['q'])) {
				$keyWords = $queryParts['q'];
				return $keyWords;
			}
			else if(isset($queryParts['p'])) {
				$keyWords = $queryParts['p'];
				return $keyWords;
			}
			else if(isset($queryParts['query'])) {
				$keyWords = $queryParts['query'];
				return $keyWords;
			}
			else if(isset($queryParts['text'])) {
				$keyWords = $queryParts['text'];
				return $keyWords;
			}
			else {
				$keyWords = ' ';
				return $keyWords;
			}
		}
	}

}